﻿using System;
using System.IO;
using System.Diagnostics;

namespace SvnTools.Tasks.VersionManagement
{
	static class ProcessTools
	{
		public static int ExecuteProcess(string filename, string workingdir, TextWriter output, TextWriter error, params string[] arguments)
		{
			ProcessStartInfo psi = new ProcessStartInfo();

			psi.FileName               = filename;
			psi.Arguments              = arguments == null ? "" : string.Join(" ", arguments);
			psi.WorkingDirectory       = workingdir;
			psi.CreateNoWindow         = true;
			psi.ErrorDialog            = false;
			psi.RedirectStandardError  = true;
			psi.RedirectStandardInput  = false;
			psi.RedirectStandardOutput = true;
			psi.UseShellExecute        = false;
			psi.WindowStyle            = ProcessWindowStyle.Hidden;

			using( Process p = new Process() )
			{
				p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { if( output != null ) output.WriteLine(e.Data); };
				p.ErrorDataReceived  += delegate(object sender, DataReceivedEventArgs e) { if( output != null ) output.WriteLine(e.Data); if( error != null ) error.WriteLine(e.Data); };
				p.EnableRaisingEvents = true;
				p.StartInfo           = psi;

				p.Start();

				p.BeginOutputReadLine();
				p.BeginErrorReadLine();

				p.WaitForExit();

				return p.ExitCode;
			}
		}

	}
}
